﻿using Hyjx.GanFengLogger;
using Hyjx.MixerService.Exceptions;
using Hyjx.MixerService.Objects;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Json;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;
using System.Threading;
using System.Threading.Tasks;

namespace Hyjx.MixerService
{
    /// <summary>
    /// 应用 Http 功能
    /// </summary>
    public class AppHttp
    {
        readonly ILogger<Mixer> _logger;
        readonly JsonSerializerOptions _jsonSerializerOptions;

        public AppHttp(ILogger<Mixer> logger)
        {
            _logger = logger;
            _jsonSerializerOptions = new JsonSerializerOptions() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
        }

        /// <summary>
        /// 检测 MES 心跳
        /// </summary>
        /// <param name="baseUrl">地址</param>
        internal async Task<bool> CheckMesHeartBeat(string url)
        {
            LogObject log = new() { DeviceCode = "上位机", InterfaceId = 200, RequestUrl = url, RequestContent = string.Empty };

            try
            {
                using HttpClient http = new();

                MesHealthResult? result = await http.GetFromJsonAsync<MesHealthResult>(url);
                if (result == null || !result.Success)
                {
                    Log.Error("检测 MES 心跳失败。");
                    return false;
                }
                return true;
            }
            catch (HttpRequestException ex)
            {
                Log.Error($"检测 MES 心跳网络异常,信息:{ex.Message}");
                return false;
            }
            catch (Exception ex)
            {
                Log.Error($"检测 MES 心跳异常,信息:{ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 发送搅拌机警报
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="args">搅拌机警告参数</param>
        internal async Task<GanFengResult?> SendMixerAlarm(string url, ReportMixerAlarmArgs args) => await HttpPostAsync(url, args.DeviceCode, 206, args).ConfigureAwait(false);

        /// <summary>
        /// 发送搅拌机实时状态
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="args">搅拌机状态参数</param>
        internal async Task<GanFengResult?> SendMixerRealStatus(string url, ReportMixerStatusArgs args) => await HttpPostAsync(url, args.DeviceCode, 207, args).ConfigureAwait(false);

        /// <summary>
        /// 发送搅拌机状态
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="args">搅拌机状态参数</param>
        internal async Task<GanFengResult?> SendMixerStatus(string url, ReportMixerStatusArgs args) => await HttpPostAsync(url, args.DeviceCode, 205, args).ConfigureAwait(false);

        /// <summary>
        /// 上传设备报警
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="args"></param>
        /// <returns></returns>
        internal async Task<GanFengSysResult?> UploadWarnStatusAsync(string url, UploadWarnStatusArgs args)
        {
            try
            {
                using HttpClient http = new();
                var serializerOptions = new JsonSerializerOptions()
                {
                    Encoder = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs, UnicodeRanges.CjkUnifiedIdeographsExtensionA)
                };
                LogObject log = new()
                {
                    DeviceCode = args.EID,
                    InterfaceId = 671,
                    RequestUrl = url,
                    RequestContent = JsonSerializer.Serialize(args, serializerOptions)
                };

                var response = await http.PostAsJsonAsync(url, args); // 提交
                GanFengSysResult? result = await response.EnsureSuccessStatusCode().Content.ReadFromJsonAsync<GanFengSysResult>();

                log.ResponseContent = JsonSerializer.Serialize(result, serializerOptions);

                GFLogger logger = new(_logger, log.DeviceCode, log.InterfaceId, log.RequestUrl, log.RequestContent, log.ResponseContent);
                logger.Append("访问成功");
                logger.CompleteWithInformation();

                return result;
            }
            catch (Exception err)
            {
                Log.Error($"调用MES接口:{url}异常,信息:{err.Message}");
                return null;
            }
        }

        async Task<GanFengResult?> HttpPostAsync(string url, string deviceCode, int interfaceId, object args)
        {
            try
            {
                using HttpClient http = new();
                var serializerOptions = new JsonSerializerOptions()
                {
                    Encoder = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs, UnicodeRanges.CjkUnifiedIdeographsExtensionA)
                };
                LogObject log = new()
                {
                    DeviceCode = deviceCode,
                    InterfaceId = interfaceId,
                    RequestUrl = url,
                    RequestContent = JsonSerializer.Serialize(args, serializerOptions)
                };

                var response = await http.PostAsJsonAsync(url, args); // 提交
                var result = await response.EnsureSuccessStatusCode().Content.ReadFromJsonAsync<GanFengResult>();

                log.ResponseContent = JsonSerializer.Serialize(result, serializerOptions);

                GFLogger logger = new(_logger, log.DeviceCode, log.InterfaceId, log.RequestUrl, log.RequestContent, log.ResponseContent);
                logger.Append("访问成功");
                logger.CompleteWithInformation();

                return result;
            }
            catch (Exception err)
            {
                Log.Error($"调用MES接口:{url}异常,信息:{err.Message}");
                return null;
            }
        }
    }
}
